import json
import os
import logging
from pathlib import Path
from typing import Dict, Optional
from pydantic import BaseModel

logger = logging.getLogger(__name__)

class PrinterConfig(BaseModel):
    name: str = ""  # 打印机名称
    is_default: bool = False

class PrinterSettings(BaseModel):
    receipt: PrinterConfig = PrinterConfig()
    label: PrinterConfig = PrinterConfig()

class PrinterSettingsManager:
    def __init__(self):
        home_dir = os.getenv('HOME') or os.getenv('USERPROFILE')  # Windows 使用 USERPROFILE
        if not home_dir:
            print("Error: Could not determine home directory")

        # 在HOME目录下创建.timerpos目录
        data_dir = Path(home_dir) / '.timerpos'
        data_dir.mkdir(exist_ok=True)
        
        # 设置数据库路径
        self.settings_file = Path(data_dir / 'printer_settings.json')
        self.settings = PrinterSettings()  # 初始化默认设置
        self._load_settings()

    def _ensure_config_dir(self):
        """确保配置目录存在"""
        config_dir = self.settings_file.parent
        config_dir.mkdir(parents=True, exist_ok=True)

    def _load_settings(self):
        """从文件加载设置"""
        try:
            self._ensure_config_dir()
            if self.settings_file.exists():
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.settings = PrinterSettings.parse_obj(data)
                logger.info("成功加载打印机设置")
            else:
                logger.info("打印机设置文件不存在，使用默认设置")
                # 确保有默认设置
                self.settings = PrinterSettings()
        except Exception as e:
            logger.error(f"加载打印机设置失败: {str(e)}")
            # 确保即使加载失败也有默认设置
            self.settings = PrinterSettings()

    def save_settings(self):
        """保存设置到文件"""
        try:
            self._ensure_config_dir()
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(self.settings.dict(), f, ensure_ascii=False, indent=2)
            logger.info("成功保存打印机设置")
        except Exception as e:
            logger.error(f"保存打印机设置失败: {str(e)}")

    def update_printer_config(self, printer_type: str, config: PrinterConfig):
        """更新打印机配置"""
        if printer_type == "receipt":
            self.settings.receipt = config
        elif printer_type == "label":
            self.settings.label = config
        else:
            raise ValueError(f"不支持的打印机类型: {printer_type}")
        
        self.save_settings()

    def get_printer_config(self, printer_type: str) -> Optional[PrinterConfig]:
        """获取打印机配置"""
        if printer_type == "receipt":
            return self.settings.receipt
        elif printer_type == "label":
            return self.settings.label
        return None

    def get_all_settings(self) -> Dict:
        """获取所有设置"""
        return self.settings.dict()

# 创建全局实例
printer_settings = PrinterSettingsManager() 